//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

interface BlockListData {
    content: string;
    items?: BlockListData[];
}

interface EditorJsBlockData {
    text?: string;
    items?: BlockListData[];
}

interface EditorJsBlock {
    data: EditorJsBlockData;
}

interface EditorJsContent {
    time: string;
    blocks: EditorJsBlock[];
    version: string;
}

function processListItem(textList: string[], itemList: BlockListData[]) {
    for (const item of itemList) {
        if (item.content.trim() != "") {
            textList.push(item.content);
        }
        if (item.items != undefined) {
            processListItem(textList, item.items);
        }
    }
}

function processBlock(textList: string[], blockData: EditorJsBlockData) {
    if (blockData.text != undefined) {
        textList.push(blockData.text);
        return;
    }
    if (blockData.items != undefined) {
        processListItem(textList, blockData.items);
    }
}

export function convertToText(srcContent: string): string {
    if (srcContent.trim() == "") {
        return "";
    }
    try {
        const textList: string[] = [];
        const obj: EditorJsContent = JSON.parse(srcContent);
        for (const block of obj.blocks) {
            processBlock(textList, block.data);
        }
        return textList.join("\n");
    } catch (e) {
        console.log(e);
        return srcContent;
    }
}